$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'goods/goodstemplate/list',
        datatype: "json",
        colModel: [
            { label: '模板id', name: 'templateId', index: 'template_id', width: 20, key: true },
            { label: '模板名称', name: 'templateName', index: 'template_name', width: 30 },
            { label: '属性id集合', name: 'attributeIds', index: 'attribute_ids', width: 30,hidden:true },
            { label: '属性名集合', name: 'attributeNames', index: 'attributeNames', width: 400 },
            { label: '是否启用', name: 'dateTemp', index: 'date_temp', width: 20,
                formatter: function (value, options, row) {
                    if (value == true) {
                        return '未启用';
                    } else if (value == false) {
                        return '已启用';
                    }
                }
            },
            { label: '创建人', name: 'createName', index: 'create_name', width: 20 },
            // { label: '是否删除', name: 'disabled', index: 'disabled', width: 10 },
            { label: '创建时间', name: 'createTime', index: 'create_time', width: 40 }
        ],
        viewrecords: true,
        height: 600,
        rowNum: 20,
        rowList : [20,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "categoryId",
            pIdKey: "parentCategoryId",
            rootPId: -1
        },
        key: {
            name: "categoryName",
            url:"nourl"
        }
    }
};
var ztree;

var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        title: null,
        goodsTemplate: {},
        goodsAttributes:{},
        selected:[],
        goodsCategory:{},
        attributeNames:[],
        q:{
            templateId:'',
            templateName:''
        },
        selectedAttributeList:[],
        influenceCraftList:[],
        tempOptionsList:[],
        tempCraftOptionsList:[],
        onlyAttributeList:[],
    },
    methods: {
        //加载商品分类树
        getGoodsCategory: function(){
            $.get(baseURL + "goodsCategory/goodscategory/select", function(r){
                ztree = $.fn.zTree.init($("#goodsCategoryTree"), setting, r.goodsCategoryEntityList);
            })
        },
        //点击弹窗三级分类选择
        goodsCategoryTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择商品分类",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#goodsCategoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //获得该分类对象,判断分类是否绑定了模板
                    //再判断三级分类是否绑定饿了模板
                    var categoryId = node[0].categoryId;
                    $.get(baseURL + "goodsCategory/goodscategory/info/"+categoryId, function(r){
                        vm.goodsCategory =  r.goodsCategory;
                        if(vm.goodsCategory.categoryLevel != '3'){
                            alert("只有三级分类才可绑定模板!")
                            return;
                        }
                        if(vm.goodsCategory.goodsType == 'fast' ||vm.goodsCategory.goodsType == 'print'  ){
                            alert("报价类的模板并不是在这里绑定!")
                            return;
                        }
                        if(!(vm.goodsCategory.templateIds == null || vm.goodsCategory.templateIds == "" || vm.goodsCategory.templateIds == undefined) ){
                            // alert("该分类下已经绑定了模板,不允许重复绑定!")
                            // return;
                            alert("该分类已有模板,重新绑定")
                        }
                        //选择上级菜单
                        vm.goodsTemplate.categoryId = node[0].categoryId;
                        vm.goodsTemplate.categoryName = node[0].categoryName;
                        layer.close(index);
                        //加载规格数据
                        vm.selectAttributeNames();
                    });
                }
            });
        },
        query: function () {
            vm.reload();
        },
        add: function(){
            vm.showList = false;
            vm.title = "新增";
            vm.goodsTemplate = {"categoryName":"请选择分类",'attributeIds':'','attributeNames':'','disabled':false};
            vm.goodsAttributes={};
            vm.selected=[];
            vm.attributeNames=[];
            vm.selectedAttributeList = [];
            vm.tempOptionsList = [];
            vm.tempCraftOptionsList = [];
            vm.onlyAttributeList = [];
            vm.getGoodsCategory();
        },
        selectAttributeNames:function(){
            //先判断是否选择了三级分类
            if(vm.goodsTemplate.categoryId == undefined){
                alert("请先选择三级分类")
                return ;
            }
            //再判断三级分类是否绑定饿了模板
            var categoryId = vm.goodsTemplate.categoryId;
            $.get(baseURL + "goods/goodsattribute/getTempGoodsAttribute/"+categoryId, function(r){
                vm.goodsAttributes =  r.attributeEntityList;
            });
        },
        //规格属性选择确认
        saveAttribute:function(){
            // var a = vm.selected.join(",");
            // vm.goodsTemplate.attributeIds = a;
        },
        updateAttribute:function(event,attributeId,attributeName){
            if(event.target.checked){
                vm.attributeNames.push(attributeName);
            }else{
                vm.attributeNames.splice(vm.attributeNames.indexOf(attributeName),1)
            }
            vm.goodsTemplate.attributeNames = vm.attributeNames.join(",");

        },
        update: function (event) {
            var templateId = getSelectedRow();
            if(templateId == null){
                return ;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.tempOptionsList = [];
            vm.tempCraftOptionsList = [];
            vm.selectedAttributeList = [];
            vm.onlyAttributeList = [];
            vm.getGoodsCategory();
            vm.getInfo(templateId)
        },
        saveOrUpdate: function (event) {
            if(vm.validator()){
                return ;
            }
            //同步ids
            // vm.goodsTemplate.attributeIds = vm.selected.join(",");
            // selectedAttributeList:[],
            //     influenceCraftList:[]
            var ids = [];
            for(var i = 0;i <vm.selectedAttributeList.length;i++){
                ids.push(vm.selectedAttributeList[i].attributeId);
            }
            vm.goodsTemplate.attributeIds = ids.join(",");
            // var influenceCraftIds = [];
            // for(var i = 0;i <vm.influenceCraftList.length;i++){
            //     influenceCraftIds.push(vm.influenceCraftList[i].attributeId);
            // }
            //influenceCraftList
            // vm.goodsTemplate.influenceCraftIds = influenceCraftIds.join(",");
            //optionIds
            var optionJson = [];
            var craftIds = [];
            var influenceCraftIds = []
            for(var i = 0;i<vm.tempOptionsList.length;i++){
                var option = {};
                option.attributeId =  vm.tempOptionsList[i].attributeId;
                var optionId = [];
                for(var j = 0;j<vm.tempOptionsList[i].selectedOptionList.length;j++){
                    optionId.push(vm.tempOptionsList[i].selectedOptionList[j]);
                }
                option.optionId = optionId;
                optionJson.push(option);
                //将影响sku总价计算的数据存入
                if(vm.tempOptionsList[i].influenceCraft){
                    vm.goodsTemplate.influenceSkuTotalPrice = vm.tempOptionsList[i].attributeId;
                }
            }
            //在这里要对tempCraftOptionsList也进行处理
            for(var i = 0;i<vm.tempCraftOptionsList.length;i++){
                var option = {};
                option.attributeId =  vm.tempCraftOptionsList[i].attributeId;
                var optionId = [];
                for(var j = 0;j<vm.tempCraftOptionsList[i].selectedOptionList.length;j++){
                    optionId.push(vm.tempCraftOptionsList[i].selectedOptionList[j]);
                }
                option.optionId = optionId;
                optionJson.push(option);
                //将影响该工艺的规格存入
                var influenceCraft = {};
                influenceCraft.craftId = vm.tempCraftOptionsList[i].attributeId;
                influenceCraft.attributeIds = vm.tempCraftOptionsList[i].influenceAttributeIds;
                influenceCraftIds.push(influenceCraft);
                //将工艺存入方便使用
                craftIds.push(vm.tempCraftOptionsList[i].attributeId);
            }
            //-----------------------------
            vm.goodsTemplate.optionJson = JSON.stringify(optionJson);
            vm.goodsTemplate.influenceCraftIds = JSON.stringify(influenceCraftIds);
            vm.goodsTemplate.craftIds = craftIds.join(",");
            console.info("vm.goodsTemplate:"+vm.goodsTemplate);
            var url = vm.goodsTemplate.templateId == null ? "goods/goodstemplate/save" : "goods/goodstemplate/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.goodsTemplate),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var templateIds = getSelectedRows();
            if(templateIds == null){
                return ;
            }
            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "goods/goodstemplate/delete",
                    contentType: "application/json",
                    data: JSON.stringify(templateIds),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function(templateId){
            $.get(baseURL + "goods/goodstemplate/info/"+templateId, function(r){
                //加载规格属性集合
                var categoryId = r.goodsCategory.categoryId;
                vm.selectedAttributeList = r.selectedAttributeList;
                vm.influenceCraftList = r.influenceCraftList;
                vm.goodsTemplate = r.goodsTemplate;
                vm.goodsTemplate.categoryName = r.goodsCategory.categoryName;
                $.get(baseURL + "goods/goodsattribute/getTempGoodsAttribute/"+categoryId, function(r){
                    vm.goodsAttributes =  r.attributeEntityList;
                    
                });
                console.log( vm.goodsAttributes);
               
                if(r.resultMap != null){
                    vm.tempOptionsList = r.resultMap.attributeVOList;
                    vm.tempCraftOptionsList = r.resultMap.craftVOList;
                    vm.onlyAttributeList = r.resultMap.attributeList;
                }
                // vm.tempOptionsList = r.tempOptionsList;
                //给tempOptionsList数据赋值
                //下列好像是多余的,留待观察
                // if(!isBlank(vm.tempOptionsList)){
                //     for(var i = 0;i<vm.goodsTemplate.optionJson.length;i++){
                //         var tempOptions = {};
                //         tempOptions.attributeId =  vm.goodsTemplate.optionJson[i].attributeId
                //         tempOptions.selectedOptionList  = vm.goodsTemplate.optionJson[i].optionId
                //     }
                // }
            });
        },
        reset:function(){
            vm.q.templateName="";
            vm.q.templateId=""
        },
        reload: function (event) {
            vm.showList = true;
            vm.goodsTemplate = {};
            vm.goodsAttributes = {};
            vm.selected = [];
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                page:page,
                postData:{
                    templateId:vm.q.templateId,
                    templateName:vm.q.templateName
                }
            }).trigger("reloadGrid");
        },
        //新增任务--模板绑定选项
        loadOption:function(){
            var attributeIds = [];
            for(var i = 0;i<vm.selectedAttributeList.length;i++){
                attributeIds.push(vm.selectedAttributeList[i].attributeId);
            }
            // var attributeIds = list.join(",");
            $.get(baseURL + "goods/goodstemplate/loadTempOptionsList/"+attributeIds, function(r){
                // vm.tempOptionsList = r.result;
                if(r.resultMap != null){
                    vm.tempOptionsList = r.resultMap.attributeVOList;
                    vm.tempCraftOptionsList = r.resultMap.craftVOList;
                    vm.onlyAttributeList = r.resultMap.attributeList;
                }
            })
        },
        //索引向上替位
        upOrder:function(index){
            // vm.selectedAttributeList
            if(index != 0){
                //和上一位的替换
                var temp1 = JSON.parse(JSON.stringify(vm.selectedAttributeList[index-1]));//上面一个的值
                var temp2 = JSON.parse(JSON.stringify(vm.selectedAttributeList[index]));//当前值
                vm.$set(vm.selectedAttributeList,index,temp1);
                vm.$set(vm.selectedAttributeList,index-1,temp2);
            }

        },
        //索引向下替位
        downOrder:function(index){
            if(index != vm.selectedAttributeList.length-1){
                //和上一位的替换
                var temp1 = JSON.parse(JSON.stringify(vm.selectedAttributeList[index+1]));//下面一个的值
                var temp2 = JSON.parse(JSON.stringify(vm.selectedAttributeList[index]));//当前值
                vm.$set(vm.selectedAttributeList,index,temp1);
                vm.$set(vm.selectedAttributeList,index+1,temp2);
            }

        },
        // 校验
        validator: function () {
            //vm.goodsTemplate
            if(isBlank(vm.goodsTemplate.templateName)){
                alert("模板名不能为空");
                return true;
            }
            //当开启的时候,校验其规格是否满足

            return false;
        }
    }
});
